package com.justgame.project.cloud.base.abs;

import com.baomidou.mybatisplus.core.toolkit.ArrayUtils;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.ArrayUtil;
import org.springframework.util.Assert;

import java.util.Arrays;
import java.util.Map;

@Slf4j
@ApiModel("短信服务基本配置")
@SuppressWarnings("all")
public abstract class AbstractSmsHandler {
    @ApiModelProperty("短信服务应用ID")
    protected final String appId;
    @ApiModelProperty("短信服务模板ID")
    protected final String templateId;
    @ApiModelProperty("请求服务地址")
    protected final String requestUrl;

    public AbstractSmsHandler(String appId, String templateId, String requestUrl) {
        this.appId = appId;
        this.templateId = templateId;
        this.requestUrl = requestUrl;
    }

    /**
     * 短信发送前调用
     */
    protected abstract void beforeSendSMS();

    /**
     * 发送短信业务逻辑
     */
    protected abstract boolean sendSMS(String phoneNumber,String[] params);

    /**
     * 发送短信后调用
     */
    protected abstract void afterSendSMS();

    /**
     * 开始执行短信发送业务逻辑
     * @param phoneNumber
     * @return
     */
    public final boolean handle(String phoneNumber,String[] params){
        // 校验手机号码
        Assert.hasLength(phoneNumber,"手机号不能为空");
        Assert.isTrue(phoneNumber.matches("^((13[0-9])|(14[5,7])|(15[0-3,5-9])|(17[0,3,5-8])|(18[0-9])|166|198|199|(147))\\d{8}$"),"手机号格式不正确");
        log.info("正在准备向["+phoneNumber+"]发送短信~");
        try{
            beforeSendSMS();
            sendSMS(phoneNumber,params);
            afterSendSMS();
            log.info("向["+phoneNumber+"]发送短信成功~");
        }catch (Exception e){
            log.info("向["+phoneNumber+"]发送短信失败~",e);
            return false;
        }
        return true;
    }

    /**
     * 短信模板Get方法接口
     * 如果实现了该接口可以统一获取不同业务逻辑下需要调用的短信模板id
     */
    public interface ISmsTemplate {
        /**
         * 手机号验证码模板id
         */
        String getAuthTemplateId();
    }
}
